package com.zephyr.nio;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileCopy {

    private static final String INPUT_FILE = "d://1.txt";
    private static final String OUTPUT_FILE = "d://2.txt";

    @Test
    public void test1() throws IOException {
        long start = System.currentTimeMillis();
        FileInputStream inputStream = new FileInputStream(INPUT_FILE);
        FileOutputStream outputStream = new FileOutputStream(OUTPUT_FILE);

        FileChannel inChannel = inputStream.getChannel();
        FileChannel outChannel = outputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (inChannel.read(buffer) != -1) {
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
        }

        inChannel.close();
        outChannel.close();
        inputStream.close();
        outputStream.close();
        System.out.println("耗时:" + (System.currentTimeMillis() - start) + "ms");
    }

    @Test
    public void test2() throws IOException {
        long start = System.currentTimeMillis();
        FileChannel inChannel = FileChannel.open(Paths.get(INPUT_FILE), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get(OUTPUT_FILE), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        outChannel.transferFrom(inChannel, 0, inChannel.size());
        inChannel.close();
        outChannel.close();
        System.out.println("耗时:" + (System.currentTimeMillis() - start) + "ms");
    }

}
